package controllers

import (
	"net/http"

	"rbac-abac-demo/models"
	"rbac-abac-demo/services"

	"github.com/gin-gonic/gin"
)

type AccessRequest struct {
	Resource string `json:"resource" binding:"required"`
	Action   string `json:"action" binding:"required"`
	Type     string `json:"type" binding:"required,oneof=rbac abac"` // rbac 或 abac
}

func CheckAccess(c *gin.Context) {
	var req AccessRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	user, _ := c.Get("user")
	u := user.(*models.User)

	var allowed bool
	switch req.Type {
	case "rbac":
		allowed = services.CheckRBAC(u, req.Resource, req.Action)
	case "abac":
		allowed = services.CheckABAC(u, req.Resource, req.Action)
	}

	c.JSON(http.StatusOK, gin.H{
		"user_id":   u.ID,
		"user_name": u.Name,
		"resource":  req.Resource,
		"action":    req.Action,
		"policy":    req.Type,
		"allowed":   allowed,
	})
}
